import datetime
import jwt
from django.conf import settings
from django.http import JsonResponse, HttpRequest
import logging
logger = logging.getLogger(__name__)

def generate_jwt_token(user_id, role):
    from datetime import datetime, timedelta, timezone
    now = datetime.now(timezone.utc)
    payload = {
        'user_id': str(user_id),
        'role': role,
        'exp': now + timedelta(hours=24),
        'iat': now,
    }
    return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')


class AuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

        self.PERMISSION_RULES = {
            '/public/': None,  # 公共接口，无需登录
            '/user/': ['customer'],  # 用户接口，需要 customer 角色
            '/order/': ['customer','merchant'],  # 订单接口（用户侧），需要 customer 角色
            '/merchant/': ['merchant'],  # 商家接口（商家侧），需要 merchant 角色
            '/info/':['customer','merchant'],
            '/employee/':['customer','merchant'],
            '/salary/':['customer','merchant'],
            '/franchise/':None,
        }

    def __call__(self, request):
        path = request.path
        # 1. 判断路径是否需要鉴权
        required_role = None
        for prefix, role in self.PERMISSION_RULES.items():
            if path.startswith(prefix):
                required_role = role
                break

        if required_role is None:
            print("required_role is None")
            return self.get_response(request)
        # 2. 获取并验证 Token
        auth_header = request.headers.get('Auth', '')
        print(request.headers)
        if not auth_header.startswith('Bearer '):
            return JsonResponse({'error': 'Missing or invalid token'}, status=401)

        token = auth_header.split(' ')[1]

        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])

            # 3. 验证 Token 内容完整性
            user_id = payload.get('user_id')
            role = payload.get('role')
            logger.error(f"{user_id},{role}", exc_info=True)
            print(user_id,role)

            if not user_id or not role:
                return JsonResponse({'error': 'Invalid token: missing required fields'}, status=401)

            request.user_id = user_id
            request.role = role  # 使用原始角色，不再兜底为 'customer'

        except jwt.ExpiredSignatureError:
            return JsonResponse({'error': 'Token has expired'}, status=401)
        except jwt.InvalidTokenError:
            return JsonResponse({'error': 'Invalid token'}, status=401)

        # 4. 校验角色权限
        if required_role and request.role not in required_role:
            return JsonResponse({'error': 'Permission denied'}, status=403)

        # 5. 放行请求
        response = self.get_response(request)
        return response





# 简化版响应处理函数
def dummy_view(request):
    return JsonResponse({
        'message': f"Access granted to {getattr(request, 'role', 'unknown')} at {request.path}"
    })


# 简化版测试请求处理器
def test_request(path, token=None, headers=None):
    request = HttpRequest()
    request.path = path
    request.method = 'GET'
    request.META = {}
    request.headers = {}

    if headers:
        for key, value in headers.items():
            request.headers[key] = value

    if token:
        request.headers['Authorization'] = f'Bearer {token}'

    middleware = AuthMiddleware(dummy_view)
    response = middleware(request)
    return response


# =============================
# ✅ 主程序入口：测试不同情况
# =============================
if __name__ == '__main__':
    # 模拟设置 Django 的 SECRET_KEY
    settings.configure()
    settings.SECRET_KEY = 'can you hear me'  # 设置一个测试用的 SECRET_KEY
    # 模拟用户 ID 和角色
    user_token = generate_jwt_token(user_id="abc123", role="customer")
    merchant_token = generate_jwt_token(user_id="merch123", role="merchant")
    fake_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx"

    print("✅ Test 1: 访问公共页面，无需登录")
    resp = test_request("/public/home")
    print(resp.content.decode())

    print("\n✅ Test 2: 普通用户访问用户页面")
    resp = test_request("/user/profile", token=user_token)
    print(resp.content.decode())

    print("\n✅ Test 3: 商家访问用户页面")
    resp = test_request("/user/profile", token=merchant_token)
    print(resp.content.decode())

    print("\n✅ Test 4: 商家访问商家页面")
    resp = test_request("/merchant/dashboard", token=merchant_token)
    print(resp.content.decode())

    print("\n❌ Test 5: 普通用户尝试访问商家页面")
    resp = test_request("/merchant/dashboard", token=user_token)
    print(resp.content.decode())

    print("\n❌ Test 6: 提供一个无效 Token")
    resp = test_request("/user/profile", token=fake_token)
    print(resp.content.decode())

    print("\n❌ Test 7: 提供一个缺少 role 字段的 Token")
    bad_payload = {
        'user_id': 'abc123',
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24),
        'iat': datetime.datetime.utcnow()
    }
    bad_token = jwt.encode(bad_payload, settings.SECRET_KEY, algorithm='HS256')
    resp = test_request("/user/profile", token=bad_token)
    print(resp.content.decode())

    print("\n❌ Test 8: 提供一个已过期的 Token")
    expired_payload = {
        'user_id': 'abc123',
        'role': 'customer',
        'exp': datetime.datetime.now(datetime.UTC) - datetime.timedelta(seconds=1),  # 已过期
        'iat': datetime.datetime.now(datetime.UTC) - datetime.timedelta(hours=1)
    }
    expired_token = jwt.encode(expired_payload, settings.SECRET_KEY, algorithm='HS256')
    resp = test_request("/user/profile", token=expired_token)
    print(resp.content.decode())